//导入 axios
import request from '../../utils/request';
import store from '../store';

//创建 reducer 函数. 将任务的列表存入到 redux 中
let todoReducer = (state=[], action) => {
  //获取 type 和 payload 值
  let {type, payload} = action;

  switch(type){
    //判断
    case 'init':
      return payload;
    //新增任务状态的操作
    case 'addTodo':
      return [...state, payload];
    //更新某个任务的完成状态
    case 'checkTodo':
      return state.map(item => {
        //比较当前任务 id 与payload 的 id 是否一致
        if(item.id === payload.id){ 
          item.done = payload.done;
        }
        return item;
      })
    //移除某个任务
    case 'removeTodo':
      return state.filter(item => item.id !== payload);
    //批量更新任务的完成状态
    case 'checkAllTodo':
      return state.map(item => {
        item.done = payload;
        return item;
      })
    default: 
      return state;
  }
}

//暴露
export default todoReducer;

//发送请求获取所有的任务   异步的 action creator
export let asyncGetTodos = () => {
  return async dispatch => {
    //发送请求获取所有的任务
    let result = await request.get('/todo');
    //更新 redux 中任务状态
    dispatch({type: 'init', payload: result});
  }
}

//声明异步的 action creator 用来新增任务
export let asyncAddTodo = (title) => {
  return async dispatch => {
    //执行异步任务了
    let result = await request.post('/tdo', {title: title, done: false});
    //更新 redux 内部的状态
    dispatch({type: 'addTodo', payload: result})
  }
}

//声明异步 action creator 更新某个任务的完成状态
export let asyncCheckTodo = (id, done) => {
  return async dispatch => {
    //发送 AJAX 请求更新某个任务的完成状态
    let result = await request.patch(`/todo/${id}`, {done: done});
    //更新 redux 中指定 id 任务的完成状态
    dispatch({type: 'checkTodo', payload: {id, done}})
  }
}

//声明异步 action creator 删除某个任务
export let asyncRemoveTodo = id => {
  return async dispatch => {
    //发送 AJAX 请求删除某个任务
    await request.delete(`/todo/${id}`);
    //同步更新 redux 中的状态
    dispatch({type: 'removeTodo', payload: id})
  }
}

//更新所有任务的完成状态
export let asyncCheckAllTodo = done => {
  return async dispatch => {
    //获得所有的任务
    let todos = store.getState().todo;
    //处理成为 promise 对象
    let promises = todos.map(item => {
      return request.patch(`/todo/${item.id}`, {done});
    });
    //批量处理
    await Promise.all(promises);
    //如果成功
    dispatch({type: 'checkAllTodo', payload: done})
  }
}


